<template>
	<u-popup bgColor="#fff" :overlayOpacity="0" :show="show" round="16" @close="closeMore"
		:customStyle="{ height: 'calc(540rpx + env(safe-area-inset-bottom))' }">
		<view class="popup_con">
			<view class="popup_header">
				<view class="left">
					<view :class="{ active_: activeIndex == index }" v-for="(item, index) in [
							props.belongingTo == 1
								? '纪念馆'
								: props.belongingTo == 2
								? '墓园'
								: props.belongingTo == 5
								? '祠堂'
								: '',
							'我的'
						]" @click="setIndex(index)">
						{{ item }}
					</view>
				</view>
				<view class="right">
					<!-- <view style="width: 260rpx">
						<u-line-progress
							:percentage="30"
							activeColor="#FBC438"
							height="16rpx"
						></u-line-progress>
					</view>
					<view class="tips">继续消费满2000币即可升级纪念馆</view>
					<view class="range">300/2000</view>
					<image src="http://112.124.50.179:8888/imgs/home/UP.png" mode=""></image> -->
					<view class="display_flex right_records" @click="
							goUrl(
								'/subPages/common/decorate_records?belongingTo=' +
									belongingTo +
									'&id=' +
									id
							)
						">
						<image :src="imgUrl + 'imgs/home/temple_records.png'" mode=""></image>
						装修记录
					</view>
				</view>
			</view>
			<view class="renovation_cemetery">
				<scroll-view scroll-x="true" :style="{ width: clientWidth + 'px' }">
					<view class="goods">
						<view class="goods_con" v-for="(item, index) in list">
							<view :class="['goods_img', item.checked && 'active']" @click="chooseItem(item, index)">
								<!-- <image
									class="goods_content"
									:src="item.decorationUrl"
									mode="center"
								></image> -->
								<!-- // 2:墓园，，5:祠堂 -->
								<view class="goods_content" :style="{
										backgroundImage: `url(${item.decorationUrl})`,
										backgroundPosition: `center ${
											belongingTo === 2
												? '-20rpx'
												: belongingTo === 5
												? '-60rpx'
												: 'center'
										}`
									}"></view>
								<view class="goods_check" v-if="item.checked">
									<image :src="imgUrl + 'imgs/worship/check.png'"></image>
								</view>
							</view>
							<view class="goods_name">{{ item.decorationName }}</view>
							<view class="goods_price" v-if="activeIndex === 0"
								:style="{ color: item.price == 0 ? '#FBC438' : '#8E775B' }">
								{{ item.price == 0 ? '免费' : item.price + '福币' }}
							</view>
							<view class="goods_time">
								<up-icon name="clock" color="#999999" size="20rpx"></up-icon>
								{{
									item.leftTime ||
									(item.lifespan == 0 ? '永久' : item.lifespan + '天')
								}}
							</view>
							<view v-if="activeIndex === 1">
								<view class="use" v-if="item.usageStatus == 2">当前使用</view>
								<view v-if="item.usageStatus == 1" class="use use_active" @click="renovateHall(item)">
									立即使用
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<Footer @sendHeight="sendHeight" @openEquip="openEquip" v-if="activeIndex == 0" :buyList="buyList"
			type="renovation" :offeringType="props.belongingTo" @queryParent="queryParent" @buy="buy" btnName="购买"
			:isShow="false" />
		<Equip ref="EquipRef" :bottom_height="bottom_height" :buyList="buyList" @del="del" />
	</u-popup>
</template>

<script setup>
	import {
		watch,
		ref,
		reactive,
		defineEmits,
		defineProps
	} from 'vue';
	import {
		imgUrl
	} from '@/external/utils/imgUrl.js';
	import Footer from '@/subPages/common/footer.vue';
	import Equip from './equip.vue';
	import {
		onReady,
		onPageScroll,
		onReachBottom
	} from '@dcloudio/uni-app';
	import HomeApi from '@/API/home/index.js';
	const homeApi = new HomeApi();

	const clientWidth = document?.body.clientWidth || uni.getSystemInfoSync().screenWidth;

	const emit = defineEmits(['close', 'query', 'previewBgc']);
	const props = defineProps({
		// 1:纪念馆，2:墓园，3:追思会，4:祭拜，5:祠堂
		belongingTo: {
			type: Number || String
		},
		id: String,
		//墓园类型 1-单人墓园，2-双人墓园
		cemeteryType: {
			type: Number,
			default: 1
		}
	});
	const tablist = ref([{
			name: '全部',
			value: 0
		},
		{
			name: '背景',
			value: 1
		},
		{
			name: '牌匾',
			value: 2
		},
		{
			name: '灵位',
			value: 3
		},
		{
			name: '音乐',
			value: 4
		}
	]);
	const show = ref(false);
	const activeIndex = ref(0);

	let buyList = ref([]);
	let LIST = ref([]);
	let list = ref([]);
	let bottom_height = ref(0);
	const EquipRef = ref();
	watch(show, (n, o) => {
		if (show) {
			query();
		}
	});
	const openEquip = (e) => {
		EquipRef.value.show = e;
	};

	/**
	 * 购买装修
	 */
	const buy = async (buyList) => {
		let params = {
			correspondingId: props.id,
			decorationDecorationIds: buyList[0].id,
			belongingTo: props.belongingTo //1纪念馆2墓园3追思会4祭拜5祠堂
		};
		let res = await homeApi.buyDecorationDecoration(params);
		if (res.code === 0) {
			uni.showToast({
				title: '购买成功，可在我的页面查看'
			});
			clear();
			emit('query');
		}
	};

	const renovateHall = (item) => {
		homeApi
			.useDecorationElementsApi({
				belongingTo: props.belongingTo,
				correspondingId: props.id,
				objectId: item.id
			})
			.then((res) => {
				if (res.code === 0) {
					query();
					emit('query');
				}
			})
			.catch(() => {});
	};
	const del = (e) => {
		list.value.forEach((ele, index) => {
			if (ele.id == e.id) {
				list.value[index].checked = false;
			}
		});
		buyList.value = e.buyList;
	};

	const goUrl = (url) => {
		uni.navigateTo({
			url: url
		});
	};

	/**
	 * 选择背景
	 */
	const chooseItem = (item, index) => {
		//我的页面，不可点击
		if (activeIndex.value === 1) {
			return;
		}

		if (list.value[index].checked) {
			//取消选中
			list.value[index].checked = false;
			const indexToRemove = buyList.value.findIndex((buyItem) => buyItem.id === item.id);
			if (indexToRemove !== -1) {
				buyList.value.splice(indexToRemove, 1);
			}
		} else {
			//选中
			const sameTypeSelected = buyList.value.find(
				(buyItem) => buyItem.classifyName === item.classifyName
			);
			if (sameTypeSelected) {
				sameTypeSelected.checked = false;
				// 如果有相同类型的已选中项，取消其选中状态
				const indexToUncheck = list.value.findIndex(
					(listItem) => listItem.id === sameTypeSelected.id
				);
				if (indexToUncheck != -1) {
					list.value[indexToUncheck].checked = false;
					// 从 buyList 中移除相同的材料类型项
					buyList.value = buyList.value.filter(
						(buyItem) => buyItem.id !== sameTypeSelected.id
					);
				}
			}
			list.value[index].checked = true;
			buyList.value.push(list.value[index]);
			//预览背景图
			emit('previewBgc', buyList.value);
		}
	};

	const setIndex = (index) => {
		activeIndex.value = index;
		query();
		clear();
	};
	const clear = () => {
		list.value?.forEach((item) => (item.checked = false));
		buyList.value = [];
	};
	const sendHeight = (e) => {
		bottom_height.value = e + 'px';
	};
	const closeMore = () => {
		activeIndex.value = 0;
		show.value = false;
		clear();
		emit('close'); // 祠堂
	};
	const setTab = (e) => {
		if (e.value == '全部') {
			list.value = LIST.value;
		} else {
			list.value = LIST.value.filter((item) => item.classifyName === e.value);
		}
	};
	/**
	 * 获取装修列表
	 */
	const query = () => {
		if (activeIndex.value == 0) {
			//装修列表
			homeApi
				.getDecorationListApi({
					belongingTo: props.belongingTo
				})
				.then((res) => {
					if (res.code === 0) {
						res.data.decorationList.forEach((ele) => {
							ele.checked = false;

							//墓园判断是单人还是双人
							if (props.belongingTo === 2) {
								if (props.cemeteryType === 1) {
									//单人墓园
									ele.decorationUrl = ele.decorationUrl.split(',')[0];
								} else if (props.cemeteryType === 2) {
									//双人墓园
									ele.decorationUrl =
										ele.decorationUrl.split(',').length > 1 ?
										ele.decorationUrl.split(',')[1] :
										'';
								}
							}
						});
						list.value = res.data.decorationList;
					}
				})
				.catch(() => {});
		} else {
			list.value = [];
			//我的装修
			homeApi
				.getUserDecorationListApi({
					belongingTo: props.belongingTo,
					correspondingId: props.id
				})
				.then((res) => {
					let isUse = 2; // 默认值设为2
					if (res.code === 0) {
						res.data.buyDecorationList?.forEach((ele) => {
							ele.checked = false;

							//墓园判断是单人还是双人
							if (props.belongingTo === 2) {
								if (props.cemeteryType === 1) {
									//单人墓园
									ele.decorationUrl = ele.decorationUrl.split(',')[0];
								} else if (props.cemeteryType === 2) {
									//双人墓园
									ele.decorationUrl =
										ele.decorationUrl.split(',').length > 1 ?
										ele.decorationUrl.split(',')[1] :
										'';
								}
							}
						});
						list.value = res.data.buyDecorationList || [];
						if (res.data.buyDecorationList) {
							for (const ele of res.data.buyDecorationList) {
								if (ele.usageStatus == 2) {
									isUse = 1;
									break; // 找到后立即退出循环
								}
							}
						}

						//添加默认背景
						let bgcImg = '';
						if (props.belongingTo == 2) {
							//墓园
							if (props.cemeteryType === 1) {
								//单人墓园
								bgcImg = imgUrl + 'imgs/home/cemetery_defaultBgc.png';
							} else if (props.cemeteryType === 2) {
								//双人墓园
								bgcImg = imgUrl + 'imgs/home/cemetery_defaultBgc.png';
							}
						} else if (props.belongingTo === 5) {
							//祠堂
							bgcImg = 'http://112.124.50.179:8888/imgs/home/temple_defaultBgc.png';
						}
						list.value.unshift({
							classifyId: 2,
							classifyName: '',
							decorationEndTime: 1741250381,
							decorationId: 19,
							decorationName: '默认背景',
							decorationUrl: bgcImg,
							id: 0,
							lifespan: '0',
							usageStatus: isUse
						});
						// LIST.value = res.data.buyDecorationList;
					}
				})
				.catch(() => {});
		}
	};
	defineExpose({
		show
	});
</script>

<style lang="scss">
	::v-deep.u-tabs__wrapper__nav__item__text {
		font-size: 28rpx !important;
	}

	.popup_con {
		background: linear-gradient(180deg, rgba(255, 234, 195, 0.4) 0%, rgba(255, 255, 255, 0) 100%),
			#ffffff;
		border-radius: 32rpx 32rpx 0 0;
		height: 600rpx;
	}

	.popup_header {
		width: 100%;
		font-size: 32rpx;
		color: #0e0e0e;
		padding: 32rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;

		.left {
			font-size: 32rpx;
			flex: 0 0 40%;
			display: flex;
			font-weight: bold;
			color: #8e775b;

			view {
				padding-right: 72rpx;
				white-space: nowrap;
			}
		}

		.right {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			flex: 1;
			position: relative;

			.right_records {
				font-weight: 400;
				font-size: 28rpx;
				color: #524630;
				line-height: 28rpx;
				flex-shrink: 0;

				image {
					width: 30rpx;
					height: 30rpx;
					margin-right: 4rpx;
				}
			}

			.range {
				padding-left: 12rpx;
				color: #666666;
				font-size: 20rpx;
			}

			image {
				padding-left: 8rpx;
				width: 18rpx;
				height: 22rpx;
			}

			.tips {
				padding: 16rpx;
				background-color: #2c2f2f;
				border-radius: 10rpx;
				position: absolute;
				top: -80rpx;
				color: #c5c5c5;
				font-size: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.tips::before {
				content: '';
				width: 0;
				height: 0;
				border: 12rpx solid;
				position: absolute;
				bottom: -20rpx;
				right: 4rpx;
				border-color: #2c2f2f transparent transparent;
			}
		}
	}

	.renovation_cemetery {
		.utabs {
			padding-left: calc(32rpx - 11px);
		}

		overflow: auto;

		.goods {
			display: flex;
			flex-wrap: nowrap;
			box-sizing: border-box;
			padding: 8rpx 0 0 32rpx;

			.goods_con {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding-right: 40rpx;

				.goods_img {
					width: 144rpx;
					height: 144rpx;
					background: #fff;
					border-radius: 8rpx;
					border: 2rpx solid #d4c6b3;
					position: relative;

					.goods_content {
						width: 100%;
						height: 100%;
						background-size: cover;
						background-repeat: no-repeat;
					}

					.goods_check {
						position: absolute;
						bottom: -2rpx;
						right: -2rpx;
						background-color: rgba(82, 70, 48, 1);
						width: 40rpx;
						height: 32rpx;
						border-radius: 16rpx 0rpx 8rpx 0rpx;
						display: flex;
						align-items: center;
						justify-content: center;

						image {
							width: 20rpx;
							height: 20rpx;
						}
					}
				}

				.active {
					border: 3rpx solid #524630;
				}

				.kuang {
					width: 96rpx;
					height: 96rpx;
					background-image: url('http://112.124.50.179:8888/imgs/home/kuang.png');
					background-repeat: no-repeat;
					background-size: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					box-sizing: border-box;

					image {
						width: 80%;
						height: 80%;
					}
				}

				.goods_name {
					font-weight: 500;
					font-size: 28rpx;
					color: #524630;
					padding-top: 16rpx;
					white-space: nowrap;
				}

				.goods_price {
					font-weight: 500;
					font-size: 24rpx;
					color: #524630;
					padding-top: 12rpx;
				}

				.goods_time {
					padding-top: 12rpx;
					color: #999999;
					font-size: 20rpx;
					display: flex;
					align-items: center;
				}

				.use {
					margin-top: 12rpx;
					width: 120rpx;
					height: 42rpx;
					border-radius: 21rpx;
					border: 2rpx solid #8e775b;
					box-sizing: border-box;
					display: flex;
					align-items: center;
					justify-content: center;
					color: #8e775b;
					font-size: 20rpx;
				}
			}
		}
	}

	.active_ {
		color: #524630 !important;
	}

	.use_active {
		color: #fff !important;
		background-color: #8e775b;
	}
</style>